package ken.app.adapter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.she.component.adapter.iface.IGenView;

public class GenView implements IGenView{
	
	Context context;
	ListView mListView;

	protected View genHeader(Context context, View convertView, Object element, int position) {
		
		return convertView;
	}
	
	protected View genBody(Context context, View convertView, Object element, int position ) {
		
		return convertView;
	}
	
	protected View genFooter(Context context) {
		return null;
	}

	@Override
	public View setup(Context context, int position, View convertView, ViewGroup parent, Object data) {
		if(data instanceof ArrayList) {
			if(position < ((ArrayList<?>)data).size()) return genBody(context, convertView, ((ArrayList<?>)data).get(position), position);
			else                                    return genFooter(context);
		} else if (data instanceof LinkedHashMap) {
			LinkedHashMap<?,?> map = (LinkedHashMap<?,?>) data;
			Iterator<?> iterator = map.entrySet().iterator();
			int index = position;
			while (iterator.hasNext()) {
				Entry<?,?> entry = (Entry<?,?>) iterator.next();
				if (entry.getValue() instanceof List) {
					if (index == 0)
						return genHeader(context, convertView, entry.getKey(), position);
					else if (index <= ((List<?>) entry.getValue()).size())
						return genBody(context, convertView, ((List<?>) entry .getValue()).get(index - 1), position);
					else
						index = index - ((List<?>) entry.getValue()).size() - 1;
				}
			}
			return genFooter(context);
		} else if (data instanceof Cursor) {
			if(position <= ((Cursor)data).getCount()) { 
				((Cursor)data).moveToPosition(position);
				return genBody(context, convertView, data, position);
			}
			else {
				return genFooter(context);
			}
		} else {
			return convertView;
		}
	}
	
	protected ListView getListView() {
		return mListView;
	}

	@Override
	public void setListview(ListView listView) {
		this.mListView = listView;
	}
}
